#include "Log.h"

#include <stdio.h>
#include <time.h>
#ifdef WIN32
#define usleep(x) Sleep(x)
#endif
#ifdef __linux__
#ifndef sprintf_s
#define sprintf_s sprintf
#endif
#endif
#include "pfunc_print.h"

namespace GlobalVar
{
	std::string logdir = "log";		//后期记录日志目录重配置文件读取
	std::string logname = "pyfree";	//可设置为服务名
};

CLogger* CLogger::m_pLogInstance = NULL;
CLogger::CLogger() 
	: running(true)
	, printf_flag(true)
	, log_file("")
{
	char buf[256] = {0};
	sprintf_s(buf,"mkdir %s",GlobalVar::logdir.c_str());
	system(buf);
	log_queue = new QueueData<log_item>();
	this->start();
};

CLogger::~CLogger()
{
	running = false;
};

CLogger* CLogger::createInstance( void )
{
	if (m_pLogInstance == NULL)
	{
		m_pLogInstance = new CLogger();
		return m_pLogInstance;
	}
	else
		return m_pLogInstance;
};

void* CLogger::run()
{
	log_item log_;
	while (running) {
		if (log_queue->pop(log_))
		{
			WriteLog(log_);
		}
		usleep(10);
	}
	return NULL;
};

void CLogger::Log(const eLogType type, const char* lpszFormat, ...)
{
	va_list args;
	//char   szBuffer[2048] = {0};
	log_item log_;
	log_.type = static_cast<int>(type);
	va_start(args, lpszFormat);
#ifdef WIN32
	vsnprintf_s(log_.szBuffer,sizeof(log_.szBuffer), lpszFormat, args);
#else
	vsnprintf(log_.szBuffer, sizeof(log_.szBuffer), lpszFormat, args);
#endif
	va_end(args); 
	log_queue->add(log_);
}


void CLogger::set_printf_flag(bool flag_)
{
	printf_flag = flag_;
}

void CLogger::WriteLog(log_item it)
{
	// Print_NOTICE("WriteLog:[%d]%s\n",it->type,it->szBuffer);
	try {
		time_t tt = time(NULL);
		struct tm tm1;
#ifdef WIN32
		localtime_s(&tm1, &tt);
#else
		localtime_r(&tt, &tm1);
#endif
		char buf[512];
		sprintf_s(buf, "%04d-%02d-%02d", tm1.tm_year + 1900, tm1.tm_mon + 1, tm1.tm_mday);
		//file name
		std::string strPath = buf;
		sprintf_s(buf,"_%s.log",GlobalVar::logname.c_str());
		strPath += std::string(buf);
		// strPath +="_gather.log";
		if(log_file!=strPath)
		{
			log_file = strPath;		
		}
		//open 后期处理成文件不变只打开一次
		strPath = GlobalVar::logdir+"/"+log_file;
		sprintf_s(buf,"%s_log",GlobalVar::logname.c_str());
		acl_msg_open(strPath.c_str(),buf);
		acl_msg_stdout_enable(printf_flag);
		//write
		switch (it.type)
		{
		case MsgInfo:
			acl_msg_info("%s",it.szBuffer);
			break;
		case MsgWarn:
			acl_msg_warn("%s",it.szBuffer);
			break;
		case MsgError:
			acl_msg_error("%s",it.szBuffer);
			break;
		case MsgFatal:
			acl_msg_fatal("%s",it.szBuffer);
			break;
		case MsgPanic:
			acl_msg_panic("%s",it.szBuffer);
			break;
		default:
			break;
		}
		//close
		acl_msg_close();
	}
	catch (...) {
		Print_WARN("write log[%d]{%s}error\n", it.type, it.szBuffer);
	}
}
